﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc.Html
{
	public static class FormatExtensions
	{
		public static int DefaultLength { get; set; }

		static FormatExtensions()
		{
			DefaultLength = 100;
		}

		public static MvcHtmlString Substring(this HtmlHelper htmlHelper, string text)
		{
			return Substring(htmlHelper, text, DefaultLength);
		}

		public static MvcHtmlString Substring(this HtmlHelper htmlHelper, string text, int length)
		{
			var container = new TagBuilder("span");
			container.AddCssClass("substring");

			if (!string.IsNullOrEmpty(text)
			    && length < text.Length)
			{
				container.Attributes.Add("title", htmlHelper.AttributeEncode(text));

				text = text.Trim().Substring(0, length).Trim();
				text += " ...";
			}

			container.SetInnerText(text);

			return MvcHtmlString.Create(container.ToString());
		}
	}
}